<?php
include("/var/www/html/new/com.inc.php");
if (!class_exists('SoapInit')) {
    include("/var/www/html/new/d/class/SoapInit.class.php");
}

if (!$_REQUEST['unlogin'] && !$_SESSION['memberID']) {
    Response("请登录后操作");
}

/**
 * 计算订单取消费用，是根据票数退款哦~
 *
 * @author GuangPeng Chen
 * @param Array $tid_price      门票ID=>价格（单位分）
 * @param Array $tid_num        门票ID=>票数
 * @param string $beginTime     订单游玩时间
 * @return array|bool|int       成功返回退票手续费，金额分
 */
function count_cost_fee( Array $tid_price, Array $tid_num, $beginTime)
{
    $tid        = array_keys($tid_price);
//    $price_arr  = array_values($tid_price);
//    print_r($tid_price);
//    print_r($tid_num);
//    $num_arr    = array_values($tid_num);
//    exit;
    $limit      = count($tid);
    if ($limit==1) {
        $where = "=" . $tid[0];
    }
    elseif($limit>1) {
        $where = 'IN(' . implode(',', $tid) . ')';
    }
    else {
        return false;
    }

    $play_date = strtotime( $beginTime . ' 00:00:00');
    $today     = strtotime(date('Y-m-d 00:00:00'));
    $day_diff  = ($play_date - $today) / 86400;//距离游玩时间的天数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额

    //使用cancel_cost字段收取手续费的供应商，目前（2014年12月19日）只有云顶
    $use_cancel_cost = array(
        7133,7134,7135,7136,
    );
    //reb_type
    $sql = "SELECT id,cancel_cost,reb,reb_type,apply_did FROM uu_jq_ticket WHERE id $where LIMIT $limit";
    $GLOBALS['le']->query($sql);
    $fee_cost = array();
//    $use_cancel_cost_flag = false;
    $total_fee = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row = $GLOBALS['le']->fetch_assoc()) {
        if (in_array($row['apply_did'], $use_cancel_cost)) {
            if (!$row['cancel_cost']) continue;
            $fee_cost[$row['id']] = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'] * $tid_num[$row['id']];
            }
            else {
                //按百分比收取手续费
//                echo "{$row['reb']} * {$tid_price[$row['id']]} * {$tid_num[$row['id']]}";
                $total_fee += ($row['reb'] * $tid_price[$row['id']] * $tid_num[$row['id']]) / 100;
            }
        }
    }
    if (count($fee_cost)) {
        foreach ($fee_cost as $tid=>$cancel_cost) {
            //取消费用一维数组 array('提前天数'=>'百分比')
            $cancel_cost_arr = json_decode($cancel_cost, true);
            $day_arr         = array_keys($cancel_cost_arr);
            sort($day_arr);
            $min_day         = min($day_arr);
            $max_day         = max($day_arr);
            if ($day_diff <= $min_day) {
                $fee = $cancel_cost_arr[$min_day];
            }
            elseif ($day_diff >= $max_day) {
                $fee = 0;
            } else {
                foreach ($day_arr as $key=>$val) {
                    if ($day_diff >= $val && $day_diff <= $day_arr[$key+1]) {
                        $fee = $day_arr[$key+1];
                        break;
                    }
                }
            }
            $total_fee += ($fee *$tid_price[$tid] * $tid_num[$tid]) / 100  ;
        }
    }
    return $total_fee;
}
/**************************请求参数**************************/
function LogRefund($txt,$file='/var/www/html/new/d/module/alipay_refund/refund_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function Response( $msg, $status = "fail") {
    $json = '{"status":"'.$status.'", "msg":"'.$msg.'"}';
    exit($json);
}

//print_r($_POST);
//处理订单数据BEGIN
if (empty($_POST['ordernum'])) {
    Response('订单号为空');
}
$ordernum = trim($_POST['ordernum']);//13
$soap = SoapInit::GetSoapInside();
$xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
    $ordernum, "", "", "", "", "", "", "1", "0", "100", "0", "0",
    "", "0", "", "0", "", "", "", "0", "0");
//echo $xml;Response;
$order_arr = simplexml_load_string($xml);
//print_r($order_arr);Response;
if (!count($order_arr)) {
    Response("订单不存在。");
}
$aid = $order_arr->Rec->UUaid;
//echo $order_arr->Rec->UUstatus;
//echo $order_arr->Rec->UUpaystatus;
//echo $order_arr->Rec->UUpmode;
//Response;
//TODO::判断订单状态，未使用，已支付
//if ($order_arr->Rec->UUstatus!=0 && $order_arr->Rec->UUpaystatus!=1 && $order_arr->Rec->UUpmode !=1 ) {
//    Response("只有已支付未使用并且是使用支付宝支付的订单方可退款。");
//}
$order_type = 0;
//TODO::判断订单类型
if ($order_arr->Rec->UUpack_order==1) {
    //套票
    $order_type = 1;
}
elseif ($order_arr->Rec->UUconcat_id>0) {
    //联票
    $order_type = 2;
}
else {
    //普通订单
}
//退款当天日期，必填，格式：年[4位]-月[2位]-日[2位] 小时[2位 24小时制]:分[2位]:秒[2位]，如：2007-10-01 13:13:13
$refund_date = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
//退票数，0表示取消订单
$tnum      = intval($_POST['num']);
$fee_cost  = 0;//取消费用
//取消订单
//print_r($order_arr);exit;
$TotalFee = 0;
if ($tnum == 0 ) {
    if ($order_type==2) {
        $xml_child  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
            $ordernum, "", "", "", "", "", "", "1", "0", "100", "0", "0",
            "", "0", "", "0", "", "", "", "1", "0","0");
        $child_order = simplexml_load_string($xml_child);
//        print_r($child_order);exit;
        foreach ($child_order as $order) {
            $tid_price[(int)$order->UUtid] = (int)$order->UUtprice;
            $tid_num[(int)$order->UUtid] = (int)$order->UUtnum;
            $TotalFee += (int)$order->UUtotalmoney;
        }
        $fee_cost = count_cost_fee($tid_price,  $tid_num, (string)$order_arr->Rec->UUbegintime);
    }
    else {
        $TotalFee += (int)$order_arr->Rec->UUtotalmoney;
        $fee_cost = count_cost_fee(
            array( (int)$order_arr->Rec->UUtid => (int)$order_arr->Rec->UUtprice),
            array((int)$order_arr->Rec->UUtid => (int)$order_arr->Rec->UUtnum),
            (string)$order_arr->UUbegintime
        );
    }
    $total_fee = $TotalFee - $fee_cost;//该笔支付订单总金额-取消费用
}
//TODO::action='GetCostFee', 返回手续费;单位：分
Response($fee_cost, "ok");